/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package control;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.*;

import javax.mail.internet.*;   // important

import javax.mail.event.*;  // important

import java.util.*;

/**
 *
 * @author woutermkievit
 */
public class MailController {

    public MailController() {
        //mail("test","test mail","wouterkievit@gmail.com");
    }

    public String mail(String text, String subject, String to) {
        Transport t = null;
        String re = "";
        try {
            String host = "smtp.gmail.com";
            String username = "three2learn.2dev@gmail.com";
            String password = "team2pdl";
            // ...
            Properties props = new Properties();
            props.setProperty("mail.host", "smtp.gmail.com");
            props.setProperty("mail.smtp.port", "587");
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.starttls.enable", "true");

            Authenticator auth = new SMTPAuthenticator(username, password);

            Session session = Session.getInstance(props, auth);
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(username));

            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
            msg.setSubject(subject);
            msg.setText(text);
            Transport.send(msg);
        } catch (Exception ex) {

            re += ex.getMessage() + "<br>";
            Logger.getLogger(MailController.class.getName()).log(Level.SEVERE, null, ex);

        }
        // set the message content here
    /*t = session.getTransport("smtps");
        t.connect(host, username, password);
        t.sendMessage(msg, msg.getAllRecipients());
        }    catch (MessagingException ex) {
        re+=ex.getMessage()+"<br>";
        Logger.getLogger(MailController.class.getName()).log(Level.SEVERE, null, ex);
        }finally {
        try {
        t.close();
        } catch (MessagingException ex) {
        
        re+=ex.getMessage()+"<br>";
        Logger.getLogger(MailController.class.getName()).log(Level.SEVERE, null, ex);
        }
        }
         */
        re += "send" + "<br>";
        System.out.println("mail has been sent");
        return re;


    }

    private class SMTPAuthenticator extends Authenticator {

        private PasswordAuthentication authentication;

        public SMTPAuthenticator(String login, String password) {
            authentication = new PasswordAuthentication(login, password);
        }

        protected PasswordAuthentication getPasswordAuthentication() {
            return authentication;
        }
    }
}
